package com.qf.im.application;

import com.qf.im.ws.MsgInHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * WebSocket的服务端
 */
@Component
@Slf4j
public class NettyWsServer {

    private static EventLoopGroup master = new NioEventLoopGroup();
    private static EventLoopGroup slave = new NioEventLoopGroup();

    @Value("${server.ws.port}")
    private Integer wsport;

    /**
     * 初始化WebSocket服务器
     */
    public void init(){
        ServerBootstrap serverBootstrap = new ServerBootstrap()
                .group(master, slave)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        
                        pipeline.addLast(new HttpServerCodec());
                        pipeline.addLast(new HttpObjectAggregator(1024 * 1024));
                        pipeline.addLast(new WebSocketServerProtocolHandler("/im"));
                        
                        //开发者自定义的ChannelHandler
                        pipeline.addLast(new MsgInHandler());
                    }
                });
        try {
            serverBootstrap.bind(wsport).sync();
            log.info("【websocket server start】websocket服务端启动成功....{}", wsport);
        } catch (InterruptedException e) {
            log.error("【websocket server error】websocket服务端启动失败....", e);
        }
    }
}
